package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.Common;
import com.sky.dto.VerifyCodeDTO;
import com.sky.entity.Rider;
import com.sky.mapper.RiderMapper;
import com.sky.service.AliyunSmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class AliyunSmsServiceImpl implements AliyunSmsService {
    @Autowired
    private Client aliyunSmsClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RiderMapper riderMapper;

    @Override
    public void SendSms(String phone) {
        try {
            Random random = new Random();
            StringBuilder code = new StringBuilder();

            for (int i = 0; i < 6; i++) {
                int digit = random.nextInt(10); // 生成0-9之间的数字
                code.append(digit);
            }
            redisTemplate.opsForValue().set("SMS_CODE:" + phone, code.toString(), 5, TimeUnit.MINUTES);
            JSONObject templateParam = new JSONObject();
            templateParam.put("code", code);

// 创建发送短信请求
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName("饿了送跑腿服务平台")
                    .setTemplateCode("SMS_305006303")
                    .setTemplateParam(templateParam.toJSONString());
            SendSmsResponse response = aliyunSmsClient.sendSms(request);

            // 输出响应
            System.out.println(Common.toJSONString(response));
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
        }
    }
    // 从 Redis 中获取验证码
    @Override
    public String verify(VerifyCodeDTO verifyCodeDTO) {
        String message="";
        String code = (String) redisTemplate.opsForValue().get("SMS_CODE:" + verifyCodeDTO.getPhone());
        if (code == null) {
            message="验证码已失效";
            System.out.println("验证码已失效");
        } else {
            if(code.equals(verifyCodeDTO.getCode())){
                Rider rider=new Rider();
                rider.setOpenid(verifyCodeDTO.getOpenid());
                rider.setPhone(verifyCodeDTO.getNewphone());
                  riderMapper.updatebyopenid(rider);
                  message="手机号更新成功";
            }else {
                message="验证码错误,请重试";
            }
            System.out.println("从Redis中获取的验证码: " + code);
        }
        return message;
    }


}
